//
//  349_两个数组的交集.swift
//  Swift-LeetCode
//
//  Created by 卢悦明 on 2024/2/20.
//

import UIKit
/**
 https://leetcode.cn/problems/intersection-of-two-arrays/description/
 1、如果用数组实现，需要nums1、nums2进行排序
 2、用集合实现，先进行数据去重，
 */
class QA349: NSObject {
    func intersection(_ nums1: [Int], _ nums2: [Int]) -> [Int] {
        var set1: Set<Int> = []
        var set2: Set<Int> = []
        nums1.forEach {
            set1.insert($0)
        }
        nums2.forEach {
            set2.insert($0)
        }
        return getIntersection(set1, set2)
    }
    func getIntersection(_ set1: Set<Int>, _ set2: Set<Int>) -> [Int] {
        if set1.count > set2.count {
            return getIntersection(set2, set1)
        }
        var intersectionSet: Set<Int> = []
        set1.forEach { item in
            if set2.contains(item) {
                intersectionSet.insert(item)
            }
        }
        var array: [Int] = []
        intersectionSet.forEach {
            array.append($0)
        }
        return array
    }
}
